import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AmazonDepartments {
	private int departmentId;
	private String departmentName;

	public int getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(int departmentId) {
		this.departmentId = departmentId;
	}

	public String getDepartmentName() {
		return departmentName;
	}

	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}
	public static AmazonDepartments getDepartment(Connection connection, String departmentName) throws SQLException{
		AmazonDepartments department = null;
		
		ResultSet rs = connection.createStatement().executeQuery("select departmentId from AmazonDepartments where departmentName ='"+departmentName.trim()+"'");
		
		while(rs.next()){
			department = new AmazonDepartments();
			department.setDepartmentId(rs.getInt(1));
			department.setDepartmentName(departmentName.trim());
		}
		if(department==null){
			PreparedStatement pr = connection.prepareStatement("insert into AmazonDepartments(departmentName) values(?) ");
			
			pr.setString(1, departmentName.trim());
			int efffectedRows= pr.executeUpdate();
			connection.commit();
			ResultSet generatedKey= pr.getGeneratedKeys();
			if(generatedKey.next()){
				department = new AmazonDepartments();
				department.setDepartmentId(generatedKey.getInt(1));
				department.setDepartmentName(departmentName.trim());
			}
			
		}
		
		return department;
	}
	
}
